package com.heima.commnet.service.Impl;

import com.heima.commnet.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CommentHotServiceImpl implements CommentHotService {

    @Autowired
    MongoTemplate mongoTemplate;
    @Async("taskExecutor")
    @Override
    public void hotCommentExecutor(ApComment apComment) {
        //查询当前文章下所有的热点评论
        Query query = Query.query(Criteria.where("articleId").is(apComment.getArticleId())
                        .and("flag").is(1))
                        .with(Sort.by(Sort.Direction.DESC,"likes"));

        List<ApComment> hotCommentList = mongoTemplate.find(query, ApComment.class);
        if (hotCommentList.size()<5){
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            return;
        }
        ApComment lastHotComment = hotCommentList.get(hotCommentList.size() - 1);
        if (apComment.getLikes()>lastHotComment.getLikes()) {
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);//设置热点评论
            lastHotComment.setFlag((short) 0);
            mongoTemplate.save(lastHotComment);//保存普通评论
        }

    }
}
